(ns clj-gallery.handler
  (:require [compojure.core :refer [defroutes routes]]
            [ring.middleware.resource :refer [wrap-resource]]
            [ring.middleware.file-info :refer [wrap-file-info]]
            [ring.middleware.defaults :refer [site-defaults]]
            [hiccup.middleware :refer [wrap-base-url]]
            [compojure.route :as route]
            [noir.util.middleware :as noir-mid]
            [noir.session :as session]
            [taoensso.timbre :as timbre]

            [clj-gallery.routes.home :refer [home-routes]]
            [clj-gallery.routes.auth :refer [auth-routes]]
            [clj-gallery.routes.upload :refer [upload-routes]]
            [clj-gallery.routes.gallery :refer [gallery-routes]]
            [clj-gallery.routes.buddy :refer [buddy-routes]]))

(println "loading handler")

(defn info-appender [{:keys [level message]}]
  (println "level:" level "message:" message))

(defn user-page [_]
  (session/get :user))

(defn init []
  (timbre/info "clj-gallery started successfully"))

(defn destroy []
  (timbre/info "clj-gallery is shutting down"))

(defroutes app-routes
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (let [ring-defaults (-> site-defaults
                          (assoc-in [:security :anti-forgery] false))]
    (-> (noir-mid/app-handler [
                               #'buddy-routes
                               ;#'auth-routes
                               ;#'home-routes
                               ;#'upload-routes
                               ;#'gallery-routes
                               #'app-routes
                               ]
                              :ring-defaults ring-defaults
                              :access-rules [user-page])
        (wrap-base-url))))
